package com.lagou.edu.service.impl;


import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.dao.LagouUserDao;
import com.lagou.edu.feign.CodeFeignClient;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.pojo.LagouUser;
import com.lagou.edu.service.SignAndRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SignAndRegisterServiceImpl implements SignAndRegisterService {

    @Autowired
    private CodeFeignClient codeFeignClient;
    @Autowired
    private LagouUserDao lagouUserDao;
    @Autowired
    private LagouTokenDao lagouTokenDao;


    @Override
    public Integer register(String email, String password, String code) {
        Integer integer = codeFeignClient.validateCode(email, code);
        if (integer == 0) {
            LagouUser lagouUser = new LagouUser();
            lagouUser.setEmail(email);
            lagouUser.setPassword(password);
            lagouUserDao.save(lagouUser);
        }
        return integer;
    }

    @Override
    public Boolean isRegistered(String email) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        Example<LagouUser> example = Example.of(lagouUser);
        List<LagouUser> all = lagouUserDao.findAll(example);
        if (all != null && all.size() > 0) {
            return true;
        }
        return false;
    }

    //
    public String login(String email, String password) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        lagouUser.setPassword(password);
        Example<LagouUser> example = Example.of(lagouUser);
        LagouUser one = lagouUserDao.findOne(example).get();
        if (one != null) {
            //登录成功
            String uuid = UUID.randomUUID().toString();
            LagouToken lagouToken = new LagouToken();
            lagouToken.setToken(uuid);
            lagouToken.setEmail(email);
            lagouTokenDao.save(lagouToken);
            return uuid;
        } else {
            throw new RuntimeException("登录失败");
        }
    }

    @Override
    public String getInfo(String token) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setToken(token);
        Example<LagouToken> example = Example.of(lagouToken);
        LagouToken token1 = lagouTokenDao.findOne(example).get();
        return token1.getEmail();
    }
}
